<?php
namespace App\Models\V1;
use DB;

class TokenModel{

    private $tokenValidTime = 2*60*60;
    /**
     * 获得token
     *
     * */
    public function  get_token_info($userId){

        //token = md5(userid+mobile+time())
        $info   = DB::table('memberinfo')->where('UserID',$userId)->first();
        $token  = $info->UserID.$info->UserName.time();
        $token  = md5($token);
        $endTime= time() + $this->tokenValidTime;
        $data  = [
            'user_id'   => $info->UserID,
            'token'     => $token,
            'end_time'  => $endTime,
            'ip'        => get_real_ip()
        ];

        DB::table('token')->insert($data);

        return ['token'=>$token,'endTime'=>$endTime];
    }


    /**
     * 刷新token
     * @param string $token token
     * */
    public function fresh_token($oldToken){
        $time   = time();
        $tokenInfo = DB::table('token')->where('token',$oldToken)->where('end_time','>',$time)->first();
        if(!$tokenInfo){
            return false;
        }
        $userId     = $tokenInfo->user_id;
        $info       = DB::table('memberinfo')->where('UserID',$userId)->first();
        $token      = $info->UserID.$info->UserName.time();
        $token      = md5($token);
        $endTime    = time() + $this->tokenValidTime;
        $datta      = [
            'token'     => $token,
            'end_time'  => $endTime,
        ];
        DB::table('token')->where('token',$oldToken)->update($datta);
        return $datta;
    }


    /**
     * 检查token
     *
     * */
    public function check_token($token){
        $time    = time();
        $tokenInfo = DB::table('token')->where('token',$token)->where('end_time','>',$time)->first();
        if($tokenInfo){
            return true;
        }else{
            return false;
        }
    }
}